import { NextRequest, NextResponse } from 'next/server';
import { HTTP_METHOD_KEY, HttpMethod } from '../decorator';
import 'reflect-metadata';

// 定义控制器类的接口
type ControllerClass = {
  new (...args: any[]): any;
  [key: string]: any;
};

/**
 * 创建通用路由处理函数
 * 这个函数将自动根据请求方法和动态路由参数找到对应的控制器方法
 */
export function createRouteHandler(controllerClass: ControllerClass) {
  return async function routeHandler(
    request: NextRequest, 
    { params }: { params: Promise<{ api: string }> }
  ) {
    try {
      const resolvedParams = await params;
      const method = request.method;
      const apiName = resolvedParams.api;

      // 获取控制器类的所有静态方法
      const methodNames = Object.getOwnPropertyNames(controllerClass)
        .filter(prop => typeof controllerClass[prop] === 'function' && prop !== 'constructor' && prop !== 'handleRequest');

      // 找到匹配当前HTTP方法和API名称的控制器方法
      for (const methodName of methodNames) {
        const httpMethod = Reflect.getMetadata(HTTP_METHOD_KEY, controllerClass, methodName);
      
        
        // 检查方法是否匹配当前HTTP方法和API名称
        if (httpMethod === method && methodName.toLowerCase().includes(apiName.toLowerCase())) {;
          try {
            // 调用控制器方法
            return await controllerClass.handleRequest(request, controllerClass[methodName]);
          } catch (err) {
            const error = err as Error;
            console.error(`处理请求时发生错误: ${error.message}`);
            console.error(error.stack);
            return NextResponse.json({ 
              message: 'Internal Server Error', 
              error: error.message 
            }, { status: 500 });
          }
        }
      }
      
      // 没有找到匹配的处理方法
      console.log(`未找到匹配的方法处理${method}请求: ${apiName}`);
      return NextResponse.json({ message: 'Not Found', method, api: apiName }, { status: 404 });
    } catch (err) {
      const error = err as Error;
      console.error(`路由处理器发生错误: ${error.message}`);
      console.error(error.stack);
      return NextResponse.json({ 
        message: 'Router Error', 
        error: error.message 
      }, { status: 500 });
    }
  };
}

/**
 * 创建所有HTTP方法的路由处理函数
 */
export function createAllMethodHandlers(controllerClass: ControllerClass) {
  const handler = createRouteHandler(controllerClass);
  
  return {
    GET: handler,
    POST: handler,
    PUT: handler,
    DELETE: handler,
    PATCH: handler,
    OPTIONS: handler,
    HEAD: handler
  };
} 